package com.cgs.query.find

import com.cgs.query.domain.QuerySource
import com.cgs.query.exception.QueryException
import com.cgs.query.handler.SourceFindHandler
import com.cgs.query.service.IQuerySourceService
import com.cgs.query.util.Utils
import mu.KotlinLogging

private val logger = KotlinLogging.logger { }

class SourceFindHandlerImpl(
        private val querySourceService: IQuerySourceService
) : SourceFindHandler {

    override fun findSourceByProjectName(projectName: String): QuerySource? {
        return querySourceService.findByProjectName(projectName)
    }

    override fun findSourceByProjectNameAndWholeName(projectName: String, wholeName: String): QuerySource? {
        return querySourceService.findById(findSourceIdByProjectNameAndWholeName(projectName, wholeName)
                ?: throw QueryException("找不到数据源:$projectName-$wholeName"))
    }

    override fun findSourceIdByProjectNameAndWholeName(projectName: String, wholeName: String): String? {
        val aliasAndDefineName = Utils.extractAliasAndDefineName(wholeName)
        return querySourceService.findSourceIdByDefineNameAndAliasAndProjectName(aliasAndDefineName.defineName, aliasAndDefineName.alias, projectName)
    }
}